<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/Dth/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
	<link href="skin/style.css" rel="stylesheet" media="screen" type="text/css" title="style" />
	<link href="skin/style_panier.css" rel="stylesheet" media="screen" type="text/css" title="style" />
	<script type="text/javascript" src="js/iframe.js"></script>
	<script type="text/javascript" src="js/ajax.js"></script>
	<script type="text/javascript" src="js/panier.js"></script>
	<script type="text/javascript" src="js/site.js"></script>
</head>
<body onload="SetTitle('Mon panier');" style="margin: 0;">
		
<?php

	$rootdir = './';
	
	include_once('functions/session.php');
	include_once('functions/panier.php');
	include_once('functions/users.php');
	include_once('functions/orders.php');
	include_once('functions/pays.php');
	include_once('paypal/paypal.php');
	include_once('functions/codespromo.php');
	include('menu_left.php');
		
?>
	<div id="panier-contenu">
		<div id="panier-header">
		</div>
		<?php echo GetPanierHTML(); ?>
	</div>

	<hr style="clear: both; visibility: hidden;"></hr>
	
</body>
</html>

<?php

	function GetPanierHTML()
	{
		if(!isset($_GET['step']))
			return GetPanierStep1HTML();
			
		switch($_GET['step'])
		{
			case 1:
				return GetPanierStep1HTML();
				
			case 2:
				if(isset($_SESSION['user']['mail']))
					return GetPanierStep3HTML();
				else
					return GetPanierStep2HTML();
					
			case 3:
				return GetPanierStep3HTML();
				
			case 4:
				return GetPanierStep4HTML();
				
			case 5:
				return GetPanierStep5HTML();
				
			default:
				return '<p>Petit rigolot.</p>';
		}
		
		return '';
	}
	
	function GetPanierStep1HTML()
	{
		return '
		<div id="panier_titre_etape1"></div>'
		. GetLignesTablePanierHTML() . (GetNumberItemsPanier() ?
		'
		<div id="panier_etape1_prix">
			Frais de port : 5 Euros*<br />
			Prix total : ' . (GetTotalPricePanier() + 5) . ' Euros
		</div>
		<br /><br /><br /><br />
		<div id="panier_commander">
			<a href="cadre_panier.php?step=2"></a>
			*France métropolitaine
		</div>
		' : '');
	}
	
	function GetPanierStep2HTML()
	{
		$HTML = '';
	
		if(isset($_POST['mail']) && isset($_POST['password']))
		{
			$user = GetUserByMail($_POST['mail']);
			
			if($user == false || strcmp($_POST['password'], $user['password']))
				$HTML .= GetPanierLoginForm('Combinaison mail / mot de passe invalide.');
			else
			{
				if($user['valid'] == 0)
				{
					$_SESSION['user'] = $user;
					$HTML .= GetPanierStep3HTML();		
				}
				else
					$HTML .= GetPanierLoginForm('Ce compte n\'est pas encore activé.');
			}
		}
		else
			$HTML .= GetPanierLoginForm('');
		
		return $HTML;
	}
	
	function GetPanierStep3HTML()
	{
		$HTML = '';
		
		if(isset($_SESSION['user']['mail']))
			$HTML .= '<script>parent.Connected = true;</script>';
		else
			return '<p style="text-align: center; margin-top: 20px;">Vous n\'êtes pas connecté</p>';
		
		$HTML .= '
			<div id="panier_titre_etape3"></div>
			<div style="margin-left: 20px; margin-top: 20px;">A quelle adresse souhaitez-vous recevoir votre commande ?</div>
			<form method="post" action="cadre_panier.php?step=4">
				<div id="panier_etape3_adressecompte">
					<div id="panier_etape3_carrebleu"></div>
					<div style="float: left; margin-left: 15px; margin-top: -1px;">
						Celle de votre compte <input onclick="PanierCheckboxClick();" style="margin-left: 10px;" type="checkbox" name="paniercheckadresse" id="paniercheckadresse" value="differente" checked/>
					</div>
				</div>
				<div id="panier_etape3_autreadresse">
					<div id="panier_etape3_carrerouge"></div>
					<div style="float: left; margin-left: 15px; margin-top: 2px;">
						Adresse différente :
					</div>
				</div>
				<table id="tableautreadresse">
					<tr>
						<td style="width: 140px;"><label for="nom">Nom</label></td>
						<td><input disabled="disabled" type="text" tabindex="1" id="nom" name="nom" size="40" /></td>
					</tr>
					<tr>
						<td><label for="prenom">Prénom</label></td>
						<td><input disabled="disabled" type="text" tabindex="2" id="prenom" name="prenom" size="40" /></td>
					</tr>
					<tr>
						<td><label for="adresse1">Adresse</label></td>
						<td><input disabled="disabled" type="text" tabindex="3" id="adresse1" name="adresse1" size="40" /></td>
					</tr>
					<tr>
						<td><label for="adresse2"></label></td>
						<td><input disabled="disabled" type="text" tabindex="4" id="adresse2" name="adresse2" size="40" /></td>
					</tr>
					<tr>
						<td><label for="codepostal">Code postal</label></td>
						<td><input disabled="disabled" type="text" tabindex="5" id="codepostal" name="codepostal" size="40" /></td>
					</tr>
					<tr>
						<td><label for="ville">Ville</label></td>
						<td><input disabled="disabled" type="text" tabindex="6" id="ville" name="ville" size="40" /></td>
					</tr>
					<tr>
						<td><label for="pays">Pays</label></td>
						<td><select disabled="disabled" name="pays" id="pays">';
		$countries = GetAllCountries();
		foreach($countries as $country)
			$HTML .= '
									<option value="' . $country['nom'] . '">' . $country['nom'] . '</option>';
		
		$HTML .= '
							</select><br />
						</td>
					</tr>
				</table>
				<p style="text-align: center; margin-top: 20px;">Si vous souhaitez laisser un message à propos de la commande, merci de l\'écrire ici :<br /><br />
					<textarea name="commentaire" rows="3" cols="70" tabindex="8"></textarea>
				</p>
				<input border=0 src="skin/bouton-panier_suivantetape3.png" type="image" name="sendorder" tabindex="12" value="Valider" id="bouton-panier_suivantetape3" />
				<div id="panier_etape3_bas" style="margin-top: 10px;"></div>
			</form>';
		
		return $HTML;
	}
	
	function GetPanierStep4HTML()
	{
		if(isset($_GET['sendorder']))
			$HTML = EnvoyerCommande();
		else
		{
			EnregistrerCommande();
			$userorder = $_SESSION['user']['currentorder'];
			
			if($userorder['frais_port_apresreduction'] == false)
				$HTML =  '<p style="margin-top: 20px; margin-left: 20px; color: red">Le pays correspondant à votre adresse de livraison ne fait pas partie
						des pays disponibles (' . $_SESSION['user']['currentorder']['adresse_pays'] . '). Impossible de poursuivre la commande.</p>';
			else
				$HTML = '
					<div id="panier_etape4_texte1">
						<div id="divinput_codepromo">
							<table>
								<tr>
									<td><input type="text" tabindex="1" id="input_codepromo" size="20"  onkeyup="PanierCheckCodePromo();" onblur="PanierCheckCodePromo();"/></td>
									<td><div id="input_codepromo-icone" class="panier_icone_codepromo_aucun"></div></td>
								</tr>
							</table>
						</div>
						<div id="panier_etape4_txtport">' . $userorder['frais_port_avantreduction'] . ' €</div>
						<div id="panier_etape4_txttotal">' . ($userorder['montantpanier_avantreduction'] + $userorder['frais_port_avantreduction']) . ' €</div>
					</div>
					<div id="panier_zone_cachee">
					</div>
					<div id="panier_etape4_texte3">
						<div id="panier_boutonpaiementetape4">
							<a href="cadre_panier.php?step=4&sendorder=1" onclick="return isChecked();"></a>
						</div>
						<div id="panier_lienconditionsventecontainer">
							<a href="site.php?pageid=8" target="_blank" id="panier_lienconditionsvente"></a>
						</div>
						<div style="margin-left: 470px;"><input id="check" type="checkbox" name="check" value="" /></div>
					</div>
				';
		}
		
		return $HTML;
	}
	
	function GetPanierStep5HTML()
	{
		$HTML = '<p style="margin-left: 20px; margin-top: 20px;">';
		if(isset($_GET['paiement']))
		{
			if($_GET['paiement'] == 'success')
			{
				if(isset($_GET['token']) && !empty($_GET['token']) && isset($_GET['PayerID']) && !empty($_GET['PayerID'])) 
				{
					$paypal = new Paypal();
					$order = GetOrderByToken($_GET['token']);
					
					if($order == false)
						$HTML .= '<p style="margin-left: 20px; margin-top: 20px">Commande introuvable</p>';
					else
					{
						$checkoutDetails = $paypal -> request('GetExpressCheckoutDetails', array('TOKEN' => $_GET['token']));

						$requestParams = array(
										'TOKEN' => $_GET['token'],
										'PAYMENTACTION' => 'Sale',
										'PAYERID' => $_GET['PayerID'],
										'PAYMENTREQUEST_0_AMT' => ($_SESSION['user']['currentorder']['montantpanier_apresreduction'] + $_SESSION['user']['currentorder']['frais_port_apresreduction']),
										'PAYMENTREQUEST_0_CURRENCYCODE' => 'EUR'
										);

						$response = $paypal -> request('DoExpressCheckoutPayment',$requestParams);
						if(is_array($response) && $response['ACK'] == 'Success') 
						{
							$transactionId = $response['PAYMENTINFO_0_TRANSACTIONID'];
							$HTML .= 'Paiement effectué, merci de votre confiance. Un mail récapitulatif vous a été envoyé.
									<script>
										UptdateNumberItemsPanier();
										parent.window.history.pushState(document.title,document.title,"/site.php");
									</script>';
							
							$user = GetUserById($order['id_user']);
							if($user != false)
								SendCommandePrisEnCompte($user['prenom'], $user['mail'], $order);
							
							$order['status'] = 2;
							ViderPanier();
							
							
							
							$code = GetCodePromoByCode($order['codepromo_code']);
							if($code)
							{
								$code['nombre']--;
								UpdateCodePromo($code);
							}
							
						}
						else
						{
							$order['status'] = 3;
							$HTML .= 'Erreur lors du paiement.';
						}
						
						UpdateOrder($order);
					}
				}
				else 
					$HTML .= 'Mauvais accès à cette page.';
			}
			else
			{
				if(isset($_GET['token']))
				{
					$order = GetOrderByToken($_GET['token']);
					
					if($order == false)
						$HTML .= 'Commande introuvable<br />';
					else
					{
						$order['status'] = 1;
						if(UpdateOrder($order) == false)
							$HTML .= 'Impossible de mettre à jour le status de la commande<br />';
					}
				}

				$HTML .= 'Votre commande a été annulée.';
			}
		}
		else
			$HTML .= 'Mauvais accès à cette page.';

		return $HTML . '</p>';
	}
	
	function GetPanierLoginForm($Erreur)
	{
		return '
			<div id="panier_titre_etape2"></div>
			<div style="margin-left: 20px; margin-top: 20px;">Pour pouvoir continuer et gérer votre commande, vous devez vous identifier :</div>	
			<div id="panier_connexion_dejainscrit">
				<div id="panier_connexion_carrebleu">
				</div>
				<div style="float: left; margin-left: 15px; margin-top: -1px;">
					Déjà inscrit :
				</div>
			</div>
			<br /><br />
			<form method="post">
				<table id="panier_connexion_table">
					<tr>
						<td><label for="mail">Adresse Mail :</label></td>
					</tr>
					<tr>						
						<td><input type="text" tabindex="1" name="mail" size="40" id="mail"/><br /></td>
					</tr>
					<tr>
						<td><label for="password">Mot de passe :</label></td>
						<td><input id="panier_submit_connexion" type="submit" name="send" tabindex="12" value="" /></td>
					</tr>
					<tr>
						<td><input type="password" tabindex="2" name="password" id="password" size="40"/><br /></td>
					</tr>
					<tr>
						<td style="text-align: right; font-size: 75%;"><a href="">Mot de passe oublié ?</a></td>
					</tr>
					<tr>
						<td><p style="color: orange;">' . $Erreur . '</p><br /><td>
					</tr>
				</table>
			</form>
			<div id="panier_connexion_creercompte">
				<div id="panier_connexion_carrerougecreercompte">
				</div>
				<div style="float: left; margin-left: 15px; margin-top: 2px;">
					Créer un compte :
				</div>
				<br />
				<br />
				<p id="panier_connexion_textecreercompte">
					Cette action vous prendra environ 1 minute, et vous permettra de gérer vos commandes, connaître leur avancement, et modifier vos données.
				</p>
			</div>
			<div id="panier_connexion_boutoncreercompte" onclick="parent.OuvrirCreerCompte();"></div>
			<div id="panier_etape2_bas" style="margin-top: 40px;"></div>
		';
	}
	
	function EnregistrerCommande()
	{
		$_SESSION['user']['currentorder'] = array();
		$User = $_SESSION['user'];
				
		$_SESSION['user']['currentorder']['id'] = $User['id'];
		$_SESSION['user']['currentorder']['order'] = GetOrderString();
		$_SESSION['user']['currentorder']['commentaire'] = $_POST['commentaire'];
		
		if(isset($_POST['paniercheckadresse']))
		{
			$_SESSION['user']['currentorder']['nom'] = $User['nom'];
			$_SESSION['user']['currentorder']['prenom'] = $User['prenom'];
			$_SESSION['user']['currentorder']['adresse_voie1'] = $User['adresse_voie1'];
			$_SESSION['user']['currentorder']['adresse_voie2'] = $User['adresse_voie2'];
			$_SESSION['user']['currentorder']['adresse_codepostal'] = $User['adresse_codepostal'];
			$_SESSION['user']['currentorder']['adresse_ville'] = $User['adresse_ville'];
			$_SESSION['user']['currentorder']['adresse_pays'] = $User['adresse_pays'];	
		}
		else
		{
			$_SESSION['user']['currentorder']['nom'] = $_POST['nom'];
			$_SESSION['user']['currentorder']['prenom'] = $_POST['prenom'];
			$_SESSION['user']['currentorder']['adresse_voie1'] = $_POST['adresse1'];
			$_SESSION['user']['currentorder']['adresse_voie2'] = $_POST['adresse2'];
			$_SESSION['user']['currentorder']['adresse_codepostal'] = $_POST['codepostal'];
			$_SESSION['user']['currentorder']['adresse_ville'] = $_POST['ville'];
			$_SESSION['user']['currentorder']['adresse_pays'] = $_POST['pays'];
		}
		
		$fp = GetFraisportByCountry($_SESSION['user']['currentorder']['adresse_pays']);
		$_SESSION['user']['currentorder']['frais_port_avantreduction'] = $fp['fraisport'];
		$_SESSION['user']['currentorder']['frais_port_apresreduction'] = $_SESSION['user']['currentorder']['frais_port_avantreduction'];
		$_SESSION['user']['currentorder']['montantpanier_avantreduction'] = GetTotalPricePanier();
		$_SESSION['user']['currentorder']['montantpanier_apresreduction'] = $_SESSION['user']['currentorder']['montantpanier_avantreduction'];
		
		$_SESSION['user']['currentorder']['codepromo_code'] = '';
		$_SESSION['user']['currentorder']['codepromo_type'] = '';
		$_SESSION['user']['currentorder']['codepromo_param'] = '';
	}
	
	function EnvoyerCommande()
	{
		if(isset($_SESSION['user']['currentorder']) == false)
			return '<p style="color: red; margin-top: 20px; margin-left: 20px;">Mauvais accès à cette page. Veuillez signaler ce problème à l\'administrateur.</p>';
		else
			$userorder = $_SESSION['user']['currentorder'];
					
		$requestParams = array(
		   'RETURNURL' => DIR_ROOT . 'site.php?pageid=7&stringparams=' . urlencode('step=5&paiement=success'),
		   'CANCELURL' => DIR_ROOT . 'site.php?pageid=7&stringparams=' . urlencode('step=5&paiement=failure')
		);

		$orderParams = array(
		   'PAYMENTREQUEST_0_AMT' => ($userorder['frais_port_apresreduction'] + $userorder['montantpanier_apresreduction']),
		   'PAYMENTREQUEST_0_SHIPPINGAMT' => $userorder['frais_port_apresreduction'],
		   'PAYMENTREQUEST_0_CURRENCYCODE' => 'EUR',
		   'PAYMENTREQUEST_0_ITEMAMT' => $userorder['montantpanier_apresreduction']
		);

		$item = array(
		   'L_PAYMENTREQUEST_0_NAME0' => GetNumberTshirtsPanier() . ' Tshirts',
		   'L_PAYMENTREQUEST_0_DESC0' => '',
		   'L_PAYMENTREQUEST_0_AMT0' => $userorder['montantpanier_apresreduction'],
		   'L_PAYMENTREQUEST_0_QTY0' => '1'
		);
		
		$config = array(
			'NOSHIPPING' => 1,
			'ALLOWNOTE' => 0,
			'SOLUTIONTYPE' => 'Sole'
		);

		$paypal = new Paypal();
		$response = $paypal -> request('SetExpressCheckout',$requestParams + $orderParams + $item + $config);

		$HTML = '';
		if(is_array($response) && $response['ACK'] == 'Success') 
		{
			$token = $response['TOKEN'];
			if(CreateOrder($userorder['id'], $userorder['order'], $userorder['nom'], $userorder['prenom'], $userorder['adresse_voie1'], $userorder['adresse_voie2'],
								$userorder['adresse_codepostal'], $userorder['adresse_ville'], $userorder['adresse_pays'], $userorder['commentaire'], $token,
								$userorder['frais_port_avantreduction'], $userorder['frais_port_apresreduction'], $userorder['montantpanier_avantreduction'], $userorder['montantpanier_apresreduction'],
								$userorder['codepromo_code'], $userorder['codepromo_type'], $userorder['codepromo_param']))
			{		
				$order = GetOrderByToken($token);
				$user = GetUserById($userorder['id']);
				$user['idscommands'] .= $order['id'] . ' ';
				UpdateUser($user);
				$_SESSION['user']['idscommands'] = $user['idscommands'];
				
				$Link = 'https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=' . urlencode($token);
				//$Link = 'https://www.paypal.com/webscr?cmd=_express-checkout&token=' . urlencode($token);
				$HTML .= '	<script>
							function Rediriger()
							{
								parent.document.location.href = "' . $Link . '";
							}
							
							setTimeout("Rediriger();", 1000);
						</script>';
			}
			else
				return '<p style="color: red; margin-top: 20px; margin-left: 20px;">Impossible de créer votre commande. Veuillez signaler ce problème à l\'administrateur.</p>';
		}
		else
			return '<p style="margin-top: 20px; margin-left: 20px;">Erreur de communication avec le site de paiement...</p>';
		
		return $HTML . '<p style="margin-top: 20px; margin-left: 20px;">Redirection vers le site de paiement...</p>';
	}
	
?>
